package com.tongtech.system.service.impl;

import com.tongtech.common.core.constant.UserConstants;
import com.tongtech.common.core.exception.ServiceException;
import com.tongtech.common.core.text.Convert;
import com.tongtech.common.core.utils.SpringUtils;
import com.tongtech.common.core.utils.StringUtils;
import com.tongtech.common.datascope.annotation.DataScope;
import com.tongtech.system.domain.ResourceStructure;
import com.tongtech.system.domain.vo.ResourceStructureTreeSelect;
import com.tongtech.system.mapper.ResourceStructureMapper;
import com.tongtech.system.service.IResourceStructureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 资源体系管理 服务实现
 *
 * @author xingyc
 */
@Service
public class ResourceStructureServiceImpl implements IResourceStructureService
{
    @Autowired
    private ResourceStructureMapper resourceStructureMapper;

    /**
     * 查询资源体系管理数据
     *
     * @param resourceStructure 资源体系信息
     * @return 资源体系信息集合
     */
    @Override
    @DataScope(deptAlias = "resourceStructure")
    public List<ResourceStructure> selectResourceStructureList(ResourceStructure resourceStructure)
    {
        return resourceStructureMapper.selectResourceStructureList(resourceStructure);
    }

    /**
     * 查询资源体系树结构信息
     *
     * @param resourceStructure 资源体系信息
     * @return 资源体系树信息集合
     */
    @Override
    public List<ResourceStructureTreeSelect> selectResourceStructureTreeList(ResourceStructure resourceStructure)
    {
        List<ResourceStructure> resourceStructures = SpringUtils.getAopProxy(this).selectResourceStructureList(resourceStructure);
        return buildResourceStructureTreeSelect(resourceStructures);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param resourceStructures 资源体系列表
     * @return 树结构列表
     */
    @Override
    public List<ResourceStructure> buildResourceStructureTree(List<ResourceStructure> resourceStructures)
    {
        List<ResourceStructure> returnList = new ArrayList<ResourceStructure>();
        List<Long> tempList = resourceStructures.stream().map(ResourceStructure::getResourceStructureId).collect(Collectors.toList());
        for (ResourceStructure resourceStructure : resourceStructures)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(resourceStructure.getParentId()))
            {
                recursionFn(resourceStructures, resourceStructure);
                returnList.add(resourceStructure);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = resourceStructures;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param resourceStructures 资源体系列表
     * @return 下拉树结构列表
     */
    @Override
    public List<ResourceStructureTreeSelect> buildResourceStructureTreeSelect(List<ResourceStructure> resourceStructures)
    {
        List<ResourceStructure> deptTrees = buildResourceStructureTree(resourceStructures);
        return deptTrees.stream().map(ResourceStructureTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据资源体系ID查询信息
     *
     * @param resourceStructureId 资源体系ID
     * @return 资源体系信息
     */
    @Override
    public ResourceStructure selectResourceStructureById(Long resourceStructureId)
    {
        return resourceStructureMapper.selectResourceStructureById(resourceStructureId);
    }

    /**
     * 根据ID查询所有子资源体系（正常状态）
     *
     * @param resourceStructureId 资源体系ID
     * @return 子资源体系数
     */
    @Override
    public int selectNormalChildrenResourceStructureById(Long resourceStructureId)
    {
        return resourceStructureMapper.selectNormalChildrenResourceStructureById(resourceStructureId);
    }

    /**
     * 是否存在子节点
     *
     * @param resourceStructureId 资源体系ID
     * @return 结果
     */
    @Override
    public boolean hasChildByResourceStructureId(Long resourceStructureId)
    {
        int result = resourceStructureMapper.hasChildByResourceStructureId(resourceStructureId);
        return result > 0;
    }


    /**
     * 校验资源体系名称是否唯一
     *
     * @param resourceStructure 资源体系信息
     * @return 结果
     */
    @Override
    public boolean checkResourceStructureNameUnique(ResourceStructure resourceStructure)
    {
        Long deptId = StringUtils.isNull(resourceStructure.getResourceStructureId()) ? -1L : resourceStructure.getResourceStructureId();
        ResourceStructure info = resourceStructureMapper.checkResourceStructureNameUnique(resourceStructure.getResourceStructureName(), resourceStructure.getParentId());
        if (StringUtils.isNotNull(info) && info.getResourceStructureId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存资源体系信息
     *
     * @param resourceStructure 资源体系信息
     * @return 结果
     */
    @Override
    public int insertResourceStructure(ResourceStructure resourceStructure)
    {
        ResourceStructure info = resourceStructureMapper.selectResourceStructureById(resourceStructure.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("资源体系停用，不允许新增");
        }
        resourceStructure.setAncestors(info.getAncestors() + "," + resourceStructure.getParentId());
        return resourceStructureMapper.insertResourceStructure(resourceStructure);
    }

    /**
     * 修改保存资源体系信息
     *
     * @param resourceStructure 资源体系信息
     * @return 结果
     */
    @Override
    public int updateResourceStructure(ResourceStructure resourceStructure)
    {
        ResourceStructure newParentResourceStructure = resourceStructureMapper.selectResourceStructureById(resourceStructure.getParentId());
        ResourceStructure oldResourceStructure = resourceStructureMapper.selectResourceStructureById(resourceStructure.getResourceStructureId());
        if (StringUtils.isNotNull(newParentResourceStructure) && StringUtils.isNotNull(oldResourceStructure))
        {
            String newAncestors = newParentResourceStructure.getAncestors() + "," + newParentResourceStructure.getResourceStructureId();
            String oldAncestors = oldResourceStructure.getAncestors();
            resourceStructure.setAncestors(newAncestors);
            updateResourceStructureChildren(resourceStructure.getResourceStructureId(), newAncestors, oldAncestors);
        }
        int result = resourceStructureMapper.updateResourceStructure(resourceStructure);
        if (UserConstants.DEPT_NORMAL.equals(resourceStructure.getStatus()) && StringUtils.isNotEmpty(resourceStructure.getAncestors())
                && !StringUtils.equals("0", resourceStructure.getAncestors()))
        {
            // 如果该资源体系是启用状态，则启用该资源体系的所有上级资源体系
            updateParentResourceStructureStatusNormal(resourceStructure);
        }
        return result;
    }

    /**
     * 修改该资源体系的父级资源体系状态
     *
     * @param resourceStructure 当前资源体系
     */
    private void updateParentResourceStructureStatusNormal(ResourceStructure resourceStructure)
    {
        String ancestors = resourceStructure.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        resourceStructureMapper.updateResourceStructureStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param resourceStructureId 被修改的资源体系ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateResourceStructureChildren(Long resourceStructureId, String newAncestors, String oldAncestors)
    {
        List<ResourceStructure> children = resourceStructureMapper.selectChildrenResourceStructureById(resourceStructureId);
        for (ResourceStructure child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            resourceStructureMapper.updateResourceStructureChildren(children);
        }
    }

    /**
     * 删除资源体系管理信息
     *
     * @param deptId 资源体系ID
     * @return 结果
     */
    @Override
    public int deleteResourceStructureById(Long deptId)
    {
        return resourceStructureMapper.deleteResourceStructureById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ResourceStructure> list, ResourceStructure t)
    {
        // 得到子节点列表
        List<ResourceStructure> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ResourceStructure tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ResourceStructure> getChildList(List<ResourceStructure> list, ResourceStructure t)
    {
        List<ResourceStructure> tlist = new ArrayList<ResourceStructure>();
        Iterator<ResourceStructure> it = list.iterator();
        while (it.hasNext())
        {
            ResourceStructure n = (ResourceStructure) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getResourceStructureId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ResourceStructure> list, ResourceStructure t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
